package com.stylefeng.guns.rest.modular.auth.util;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.net.ftp.FTPClient;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * @创建人 lIUJF
 * @创建时间 2019/1/11
 * @描述: 连接ftp服务器
 */
@Slf4j
@Data
@Configuration
@ConfigurationProperties(prefix = "ftp")
public class FTPUtil {
	private String hostName ;//地址
	private Integer port;//地址
	private String userName;//账户名
	private String password;//密码

	private FTPClient ftpClient = null;

	//初始化ftpClient
	private void initFTPClient(){
		try{
			ftpClient = new FTPClient();
			ftpClient.setControlEncoding("utf-8");
			ftpClient.connect(hostName,port);
			ftpClient.login(userName,password);
		}catch (Exception e){
			log.error("初始化FTP失败",e);
		}
	}

	//输入一个路径将路径里的文件转换字符串返回
	public String getFileByAddress(String fileAddress){
		BufferedReader bufferedReader = null;
		try {
			initFTPClient();
			bufferedReader = new BufferedReader(
					new InputStreamReader(
							ftpClient.retrieveFileStream(fileAddress))
			);
			StringBuffer stringBuffer = new StringBuffer();
			while (true) {
				String lineStr = bufferedReader.readLine();
				if (lineStr == null) {
					break;
				}
				stringBuffer.append(lineStr);
			}
			ftpClient.logout();
			return stringBuffer.toString();
		} catch (Exception e) {
			log.error("获取文件路径失败", e);
		} finally {
			try {
				bufferedReader.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return null;
	}

	public static void main(String[] args){
		FTPUtil ftpUtil=new FTPUtil();
		String fileByAddress = ftpUtil.getFileByAddress("seats/cgs.json");
		System.out.println(fileByAddress);
	}
}
